package org.breathe.dynamic.thread.pool.starter.mysql.refresh;

/**
 * @author: breathe
 * @createTime: 2025-05-19
 */

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.breathe.dynamic.thread.pool.core.refresh.AbstractRefresher;
import org.breathe.dynamic.thread.pool.starter.mysql.config.MysqlConfigProvider;
import org.breathe.thread.pool.common.entity.BreatheDtpProperties;
import org.breathe.thread.pool.common.enums.ConfigFileTypeEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 从 MySQL 拉取配置并刷新线程池
 */
@Slf4j
@Component
public class MysqlRefresher extends AbstractRefresher implements InitializingBean {

    private static final ScheduledExecutorService EXECUTOR = new ScheduledThreadPoolExecutor(5);

    @Autowired
    private BreatheDtpProperties breatheDtpProperties;
    @Autowired
    private MysqlConfigProvider mysqlConfigProvider;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private String lastConfig;

    /**
     * 刷新线程，五秒刷新一次配置
     */
    @Override
    public void afterPropertiesSet() {
        long refreshInterval = breatheDtpProperties.getMysql().getRefreshInterval();
        //首次启动将配置存进去
        try {
            if (saveConfig(breatheDtpProperties) == 0) {
                log.error("save count == 0");
                log.error("数据库交互错误，无法进行保存和更新");
                return ;
            }
        } catch (RuntimeException e) {
            log.error(e.getMessage());
            log.error("数据库交互错误，无法进行保存和更新");
            return ;
        }
        Set<Integer> set = new HashSet<>();
        lastConfig = JSON.toJSONString(breatheDtpProperties);
        EXECUTOR.scheduleWithFixedDelay(this::doRefresh, 0, refreshInterval, TimeUnit.SECONDS);
        log.info("breathe dynamicTp mysql refresher started, interval = {}ms", refreshInterval);
    }
    private void doRefresh() {
        try {
            String configJson = mysqlConfigProvider.getConfigJson();
            if (Objects.equals(configJson, lastConfig)) {
                return ;
            }
            lastConfig = configJson;
            refresh(configJson, ConfigFileTypeEnum.JSON);
            log.info("breathe dynamicTp mysql refresher refreshed.");
        } catch (Exception e) {
            log.error("breathe dynamicTp mysql refresher error", e);
        }
    }
    private int saveConfig(BreatheDtpProperties breatheDtpProperties) {
        String columnName = breatheDtpProperties.getMysql().getColumnName();
        String tableName = breatheDtpProperties.getMysql().getTableName();
        String configKey = breatheDtpProperties.getMysql().getConfigKey();
        String configValue = breatheDtpProperties.getMysql().getConfigValue();
        String properties = JSON.toJSONString(breatheDtpProperties);
        String sql = "INSERT INTO " + tableName + " (" + configKey + ", " + columnName + ") " + "VALUES (?, ?) ON DUPLICATE KEY UPDATE " + columnName + " = VALUES(" + columnName + ")";
        return jdbcTemplate.update(sql, configValue, properties);
    }
}